<?php
/**
 * Created by PhpStorm.
 * User: ivi
 * Date: 2019/2/23
 * Time: 17:48
 */

namespace App\Http\Requests\Admin\System;


use App\Http\Requests\BaseFormRequest;
use App\Models\System\Group;
use App\Models\System\User;
use Illuminate\Validation\Rule;

class UserSaveFormRequest extends BaseFormRequest
{
    protected function passedValidation()
    {
        $hospital_ids = $this->get('hospital_ids');
        if (!empty($hospital_ids)) {
            $this->offsetSet('hospital_ids', implode(',', $hospital_ids));
        } else {
            $this->offsetSet('hospital_ids', '');
        }
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $id = $this->get('id', 0);
        $roles = [
            'username' => [
                'required',
                Rule::unique(User::class, 'username')->where('deleted_at', 0)->ignore($id)
            ],
            'role_id' => [
                'required',
            ],
            'group_code' => [
                'required',
            ]
        ];

        if ($id) {
            $password = $this->get('password');
            if (!empty($password)) {
                $roles['password'] = ['between:6,255', 'confirmed'];
            }
        } else {
            $roles['password'] = ['required', 'between:6,255', 'confirmed'];
        }

        return $roles;
    }

    public function messages()
    {
        return __('system.user.validation');
    }
}
